package com.jt.provider.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.jt.provider.server.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicLong;

@RestController
public class ProviderSentinelController {

    @GetMapping("/provider/sentinel01")
    public String doSentinel01(){
        return "sentinel test 01";
    }
    @GetMapping("/provider/sentinel02")
    public String doSentinel02(){
        return "sentinel test 02";
    }
    @Autowired
    private ResourceService resourceService;
    @GetMapping("/provider/sentinel03")
    public String doSentinel03(){
        return resourceService.doGetResource();
        //return "sentinel test 03";
    }
    @GetMapping("/provider/sentinel04")
    public String doSentinel04(){
        resourceService.doGetResource();
        return "sentinel test 04";
    }
    //private int count; count++有多步骤，无原子性，多线程会抢，线程不安全
    //原子包，变成原子性，自增，自减是线程安全的，效率较好，无需枷锁
    private AtomicLong atomicLong = new AtomicLong(1);
    @GetMapping("/provider/sentinel05")
    public synchronized String doSentinel05() throws Exception{
        Long count = atomicLong.getAndIncrement();  //先取值再加1
        if(count%2==0){
            Thread.sleep(200); //模拟耗时操作
        }
        return "sentinel test 05";
    }
    @GetMapping("/provider/sentinel06")
    //如果不加的话，在页面就不会进行标识,调用@RequestParam里面的资源
//    @SentinelResource("selectById")
    public String doSentinel06(@RequestParam("id") Integer id){
        return resourceService.doGetResource(id);
//        return "sentinel test 06,id="+id;

    }
}
